package com.qf.chat.commons.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;

@Component
public class EmailUtils {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String username;

    //注入线程池
    @Autowired
    private ThreadPoolExecutor executor;

    //发送邮件
    public void sendEmailCode(String email, int code){
        //提交一个任务给线程池
        executor.submit(() -> {
            //创建一封邮件
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //创建一个装饰对象
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);

            try {
                //设置邮件标题
                helper.setSubject("【腾讯官方】密码找回邮件");
                //设置邮件发送方
                helper.setFrom(username);
                //设置邮件的接收方
                //to - 接收方
                //cc - 抄送方
                //bcc - 密送方
                helper.setTo(email);
//            helper.setCc();
//            helper.setBcc();

                //设置邮件的内容
                helper.setText("您的验证码是：<font color='red' style='font-size:40px'>" + code + "</font>，如果非本人操作，请忽略。", true);
                //设置发送时间
                helper.setSentDate(new Date());

                //发送邮件
                mailSender.send(mimeMessage);
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        });

    }
}
